package com.example.mychat.Service;

import com.example.mychat.Dao.userDao;
import com.example.mychat.Dao.wsDao;
import com.example.mychat.Pojo.NewFriend;
import com.example.mychat.Pojo.Result;
import com.example.mychat.Pojo.UserInfo;
import com.example.mychat.Utils.UserSessionRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

@Service
@Slf4j
public class FriendService {
    @Autowired
    private userDao userdao;
    @Autowired
    private UserSessionRegistry userSessionRegistry;
    @Autowired
    private wsDao wsdao;

    /**
     * 添加好友--发送好友请求
     * @param newFriend
     * @return
     */
    public Result FriendAdd(NewFriend newFriend) {
        String mes;
        Result result = null;
//        根据好友id查找
//        转发添加好友请求
        int changeline = userdao.New_friends(newFriend);
        if (changeline > 0) {
            UserInfo user = userdao.selectUser(newFriend.getSendId());
            String tomes="add"+":"+user.getId()+","+user.getName()+","+user.getLogo();
            try{
               WebSocketSession webSocketSession= userSessionRegistry.getSessionId(newFriend.getToId());
               if(webSocketSession!=null && webSocketSession.isOpen()){
                   webSocketSession.sendMessage(new TextMessage(tomes));
                   log.info("正在向"+userSessionRegistry.getSessionId(newFriend.getToId())+"发送消息");
                   log.info("---好友请求已发送");
               }
            }catch(Exception e){
                e.printStackTrace();
                log.info("好友请求发送失败了！");
            }
            mes = "好友请求已发送！";
            result = Result.success(mes);
        } else {
            mes = "请求发送失败";
            result = Result.error(mes);
        }
        return result;
    }

    /**
     * 好友列表查询
     * @param myId
     * @return
     */
    public List<UserInfo> SelectFriendInfo(String myId){
        List<UserInfo> myfriendinfo=userdao.MyfriendInfoSelect(myId);
        return myfriendinfo;
    }

    /**
     * 新朋友友查找
     * @param input
     * @return
     */
    public UserInfo checknewfriend(String input){
        UserInfo userinfo=userdao.selectUser(input);
        return userinfo;
    }

    public Result getmynewFriendList(String myId){
        Result result=null;
        try {
            List<UserInfo> list=userdao.getmynewfriendlist(myId);
            result=Result.success(list);
        }catch(Exception e){
            log.info(e.toString());
            result=Result.error("好友验证消息获取失败！");
        }
        return result;
    }



    /**
     * 确认好友添加请求
     * @param newFriend 实体类
     * @return
     */
    public Result confirmFriendRequest(NewFriend newFriend){
        Result result=null;
        String state=newFriend.getState();
        if(state.equals("1")){
            //代表验证已通过
            String sendId= newFriend.getSendId();
            String toId= newFriend.getToId();
            //生成chatId
            String chatId='p'+sendId+toId+'p';
            int res=updataaddfriend(newFriend,sendId,toId,chatId);
            if(res==0){
                result=Result.error("系统错误！");
                log.info("执行失败，已回滚");
            }else{
                result=Result.success("好友添加成功");
            }
        }else if(state.equals("2")){
            result=userdao.u_confirmFriendRequest(newFriend)>0?Result.success("好友申请已拒绝"):Result.error("系统错误！");

        }
        return result;
    }

    /**
     * 好友删除操作
     * @param newFriend 实体类，用于获取好友信息
     * @return
     */
    public Result deleteFriend(NewFriend newFriend){
        Result result=null;
        int transOfres=deleteFriend_trans(newFriend);
        if(transOfres>0){
            result=Result.success("好友删除成功！");
        }else{
            result=Result.error("系统错误，好友删除失败！");
        }
        return result;
    }

    /**
     * 添加好友事务，确保方法内的操作全部执行成功，否则回滚
     * @param sendId
     * @param toId
     */
    @Transactional
    public int updataaddfriend(NewFriend newFriend,String sendId,String toId,String chatId){
        log.info("正在执行事务："+toId+':'+sendId);
        int p1=userdao.u_confirmFriendRequest(newFriend);
        int p2=userdao.FriendAdd(sendId,toId);
        int p3=userdao.FriendAdd(toId,sendId);
        String member=sendId+','+toId;
        String name1=userdao.selectUser(sendId).getName();
        String name2=userdao.selectUser(toId).getName();
        String chatname=name1+'，'+name2;
        int p4=wsdao.mapInsert(chatId,member,chatname);
        wsdao.MesInsert_person("恭喜已添加为好友",chatId);
        return p1+p2+p3+p4;
    }

    /**
     * 删除好友事务
     * @param newFriend
     * @return
     */
    @Transactional
    public int deleteFriend_trans(NewFriend newFriend){
        int d2 = 0;
        String chatId=wsdao.chatIdSelect(newFriend.getToId(), newFriend.getSendId());
        int d1=userdao.MapDelete(newFriend.getSendId(), newFriend.getToId());
        try{
            d2=userdao.deletefromperson(chatId);
        }catch(Exception e){
            log.info(e.toString());
        }
        int u1=userdao.updateUser_friend(newFriend.getSendId(), newFriend.getToId());
        int u2=userdao.updateUser_friend(newFriend.getToId(), newFriend.getSendId());
        return d1+d2+u1+u2;

    }

}
